package org.zzh.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.zzh.dao.mapper.PeRoleMapper;
import org.zzh.dao.mapper.PeUserMapper;
import org.zzh.domain.system.module.SsModule;
import org.zzh.domain.system.user.PeUser;
import org.zzh.service.system.module.SsModuleService;
import org.zzh.service.system.role.PeRoleService;
import org.zzh.service.system.user.PeUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


public class MyRealm extends AuthorizingRealm {

    @Autowired
    private PeUserService peUserService;

    @Autowired
    private PeRoleService peRoleService;

    @Autowired
    private SsModuleService ssModuleService;

    @Autowired
    private HttpServletRequest request;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String email = token.getPrincipal().toString();
        PeUser user = peUserService.findByEmail(email);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        String password = user.getPassword();
        request.getSession().setAttribute("user", user);
        return new SimpleAuthenticationInfo(email, password, "");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        PeUser user = peUserService.findByEmail(username);
        List<String> userRoleIds = peRoleService.getUserRoleIds(user.getUserId());
        List<SsModule> moduleList = ssModuleService.listByRoleIds(userRoleIds.toArray(new String[0]));
        if (moduleList != null) {
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            for (SsModule module : moduleList) {
                authorizationInfo.addStringPermission(module.getName());
            }
            return authorizationInfo;
        }
        return null;
    }
}